///
//  IAPHelper.m
//  DrawChartTest
//
//  Created by FrankLiu on 16/7/5.
//  Copyright © 2016年 FrankLiu. All rights reserved.
//

#import "IAPHelper.h"
#import "WHttpTool.h"
#import "AppDelegate.h"

@interface IAPHelper ()

@property (nonatomic, strong) SKProductsRequest *m_request;

@end

@implementation IAPHelper

+ (IAPHelper *)sharedData{
    static IAPHelper *shareData = nil;
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        shareData = [[self alloc] init];
        [[SKPaymentQueue defaultQueue]addTransactionObserver: shareData];
    });
    return shareData;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)requestProductData {
    
    NSArray *product = nil;
    switch (self.m_buyType) {

        case ID_Coin1:
            product=[[NSArray alloc] initWithObjects:ProductID_Coin1,nil];
            break;
        case ID_Coin2:
            product=[[NSArray alloc] initWithObjects:ProductID_Coin2,nil];
            break;
        case ID_Coin3:
            product=[[NSArray alloc] initWithObjects:ProductID_Coin3,nil];
            break;
        case ID_Coin4:
            product=[[NSArray alloc] initWithObjects:ProductID_Coin4,nil];
            break;
//        case ID_Coin5:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin5,nil];
//            break;
//        case ID_Coin6:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin6,nil];
//            break;
//        case ID_Coin7:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin7,nil];
//            break;
//        case ID_Coin8:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin8,nil];
//            break;
//        case ID_Coin9:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin9,nil];
//            break;
//        case ID_Coin10:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin10,nil];
//            break;
//        case ID_Coin11:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin11,nil];
//            break;
//        case ID_Coin12:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin12,nil];
//            break;
//        case ID_Coin13:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin13,nil];
//            break;
//        case ID_Coin14:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin14,nil];
//            break;
//        case ID_Coin15:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin15,nil];
//            break;
//        case ID_Coin16:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin16,nil];
//            break;
//        case ID_Coin17:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin17,nil];
//            break;
//        case ID_Coin18:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin18,nil];
//            break;
//        case ID_Coin19:
//            product=[[NSArray alloc] initWithObjects:ProductID_Coin19,nil];
//            break;

        case ID_GoldA:
            product=[[NSArray alloc] initWithObjects:ProductID_GoldA,nil];
            break;
        case ID_GoldA1:
            product=[[NSArray alloc] initWithObjects:ProductID_GoldA1,nil];
            break;
        case ID_SilverA:
            product=[[NSArray alloc] initWithObjects:ProductID_SilverA,nil];
            break;
        case ID_SilverA1:
            product=[[NSArray alloc] initWithObjects:ProductID_SilverA1,nil];
            break;
        case ID_CommonA1:
            product=[[NSArray alloc] initWithObjects:ProductID_CommonA1,nil];
            break;
        case ID_CommonA2:
            product=[[NSArray alloc] initWithObjects:ProductID_CommonA2,nil];
            break;
        case ID_CommonB1:
            product=[[NSArray alloc] initWithObjects:ProductID_CommonB1,nil];
            break;
        case ID_CommonB2:
            product=[[NSArray alloc] initWithObjects:ProductID_CommonB2,nil];
            break;
        case ID_CommonC1:
            product=[[NSArray alloc] initWithObjects:ProductID_CommonC1,nil];
            break;
        case ID_CommonC2:
            product=[[NSArray alloc] initWithObjects:ProductID_CommonC2,nil];
            break;

        case ID_ProductA:
            product=[[NSArray alloc] initWithObjects:ProductID_ProductA,nil];
            break;
        case ID_ProductB:
            product=[[NSArray alloc] initWithObjects:ProductID_ProductB,nil];
            break;
        case ID_StudyA:
            product=[[NSArray alloc] initWithObjects:ProductID_StudyA,nil];
            break;
        case ID_StudyB:
            product=[[NSArray alloc] initWithObjects:ProductID_StudyB,nil];
            break;
        case ID_StudyC:
            product=[[NSArray alloc] initWithObjects:ProductID_StudyC,nil];
            break;
        default:
            break;
    }

    [WShareUtil sharedData].productId = product[0];
    NSSet *set = [NSSet setWithArray:product];
    
    self.m_request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
    self.m_request.delegate = self;
    [self.m_request start];

}

//交易结果
- (void)paymentQueue: (SKPaymentQueue *)queue updatedTransactions: (NSArray *)transactions
{
    for(SKPaymentTransaction *transaction in transactions)
    {
        WLog(@"%@___transaction",transaction.payment.applicationUsername);
        WLog(@"%@___transaction",transaction.payment.productIdentifier);

        switch(transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchasing:
                WLog(@"商品添加进列表");
                break;
            case SKPaymentTransactionStatePurchased:
//                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];//记得关闭交易事件
                [self completeTransaction: transaction Purchasing:nil];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction: transaction];
                [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
                break;
            case SKPaymentTransactionStateRestored:
                WLog(@"恢复购买");
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            default:
                [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
                break;
        }
    }
}

- (void)completeTransaction: (SKPaymentTransaction *)transaction Purchasing:(BOOL)Purchasing{
    
    WLog(@"%@",transaction.transactionIdentifier);

    NSString * productIdentifier = transaction.payment.productIdentifier;
    // 从沙盒中获取到购买凭据
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receipt = [NSData dataWithContentsOfURL:receiptURL];
    NSString *strReceipt = [receipt base64EncodedStringWithOptions:0];

    if ([productIdentifier length] > 0) {

        if ([WShareUtil sharedData].isMember == NO) {
            [self requestSubmitBuyInfoData:strReceipt transaction:transaction];
        } else {

            [self reportTestMemberInfo:strReceipt transaction:transaction];
        }
    }
}

- (void)failedTransaction: (SKPaymentTransaction *)transaction
{

    [WShareUtil sharedData].isWDDD = NO;

    if(transaction.error.code != SKErrorPaymentCancelled) {
        [WShareUtil showAlert:@"温馨提示" message:@"购买失败"];
        WLog(@"购买失败");
    } else {
        WLog(@"用户取消交易");
    }
    [WShareUtil showWait:NO frame:CGRectZero];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

#pragma mark - SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    
    self.m_request = nil;
    
    WLog(@"-----------收到产品反馈信息--------------");
    NSArray *myProduct = response.products;
    
    if ([myProduct count] == 0) {
        //        [SVProgressHUD dismiss];
        WLog(@"没有该商品");
        [WShareUtil showAlert:@"温馨提示" message:@"没有该商品"];
        [WShareUtil showWait:NO frame:CGRectZero];
        return;
    }
    WLog(@"产品Product  ID:%@",response.invalidProductIdentifiers);
    WLog(@"产品付费数量: %d", (int)[myProduct count]);
    // populate UI
    for(SKProduct *product in myProduct){
        WLog(@"product info");
        WLog(@"SKProduct 描述信息%@", [product description]);
        WLog(@"产品标题 %@" , product.localizedTitle);
        WLog(@"产品描述信息: %@" , product.localizedDescription);
        WLog(@"价格: %@" , product.price);
        WLog(@"Product id: %@" , product.productIdentifier);
        
        SKPayment *payment = [SKPayment paymentWithProduct:product];
        [[SKPaymentQueue defaultQueue] addPayment:payment];

    }
}

#pragma mark - SKRequestDelegate
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    
    UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",NULL) message:[error localizedDescription]
                                                       delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
    [alerView show];
    [WShareUtil showWait:NO frame:CGRectZero];
}

- (void)dealloc {
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];//解除监听
}

- (void)requestSubmitBuyInfoData:(NSString *)receipt transaction:(SKPaymentTransaction *)transaction {

    if (receipt == nil) {
        receipt = @"";
    }

    NSMutableDictionary *dtoDic;

    WLog(@"%@",[WShareUtil sharedData].orderId);
    WLog(@"%@",[WShareUtil sharedData].dicMinvoice);
    WLog(@"%@",[WShareUtil sharedData].dicOrder);

    NSString *orderId;
    NSString *productId;

    if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].dicOrder[@"orderId"]]) {
        if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].orderId]) {
            orderId = @"";
        } else {
            orderId = [WShareUtil sharedData].orderId;
        }
    } else {
        orderId = [WShareUtil sharedData].dicOrder[@"orderId"];
    }

    if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].productId]) {
        productId = @"";
    } else {
        productId = [WShareUtil sharedData].productId;
    }

    if ([WShareUtil sharedData].dicMinvoice) {
        [WShareUtil sharedData].dicMinvoice[@"receipt"] = receipt;
        [WShareUtil sharedData].dicMinvoice[@"goodtype"] = @"course";
        [WShareUtil sharedData].dicMinvoice[@"orderId"] = orderId;

        dtoDic = [[WShareUtil sharedData].dicMinvoice mutableCopy];
        dtoDic[@"transaction_id"] = transaction.transactionIdentifier;

    } else {

        NSDictionary *dicDto = @{@"cat":@"0",@"EMAIL":@"",@"KPLX":@"4",@"KPMC":@"",@"KPSH":@"",@"LXDH":@"",@"LXR":@"",@"productId":productId,@"productNum":@"1",@"BZ":@"",@"receipt":receipt,@"goodtype":@"course",@"orderId":orderId,@"transaction_id":transaction.transactionIdentifier};
        dtoDic = [dicDto mutableCopy];
    }

    NSString *username;
    NSString *nologinuser;
    NSDictionary *parametersDict;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"revert":@"iosorder",@"username":username,@"apptype":@"ios",@"dto":dtoDic}};

    }else {
        nologinuser = [WShareUtil getUUID];
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"revert":@"iosorder",@"apptype":@"ios",@"nologinuser":nologinuser,@"dto":dtoDic}};

    }
        // 字典转JSON字符串
        NSString *jsonData = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
        // 加密JSON字符串
        WLog(@"加密JSON字符串的结果%@",[CommonFunc encryptWithText:jsonData]);//加密方法
        WLog(@"解密乱码后的结果%@",[CommonFunc decryptWithText:@"sZjh+Dfxf1kcn5u4bgq4g75bHbBQ6DlL2oF3ELtxXb8dkwb1w5GRyfm7huCriDvlsdsFDoOWLqzX7tt+NpCuiEApxy+2QONMEZpGLBejk+1ZPreDtd3O7Q=="]);//解密方法

        // 加密后字典参数
        NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:jsonData]};
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:paramsDic success:^(id responseObject) {

        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
      
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {
            [WShareUtil sharedData].dicOrder = returnDic;
            [WShareUtil showAlert:@"温馨提示" message:@"购买成功"];

            [[NSNotificationCenter defaultCenter] postNotificationName:@"AccoutRefresh" object:@{@"price":returnDic[@"price"]}];

//            [[NSNotificationCenter defaultCenter] postNotificationName:@"MyOrderRefresh" object:nil];

//           if (![WShareUtil sharedData].isWDDD) {
//               NSString *strId;
//               if ([WShareUtil strNilOrEmpty:returnDic[@"KC_ID"]]) {
//                   strId = @"";
//               }else {
//                   strId = returnDic[@"KC_ID"];
//               }
//               [WShareUtil sharedData].dicBuySymbol = @{@"boughten":@"1",@"chosen":@"0",@"id":strId};
//           }

        } else {
            [WShareUtil showAlert:@"温馨提示"	 message:returnDic[@"errorInfo"]];
        }
        [WShareUtil sharedData].isWDDD = NO;

        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

        [[NSNotificationCenter defaultCenter] postNotificationName:@"PaySuccess" object:nil];

        [WShareUtil showWait:NO frame:CGRectZero];

    } failure:^(NSError *error) {
        WLog(@"服务器验证失败");
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        [WShareUtil showWait:NO frame:CGRectZero];

        [[NSNotificationCenter defaultCenter] postNotificationName:@"PayFlase" object:nil];
        [WShareUtil sharedData].isWDDD = NO;

        WLog(@"请求失败");
    } showProgress:NO];
}

#pragma mark 订单验证接口
- (void)reportTestMemberInfo:(NSString *)receipt transaction:(SKPaymentTransaction *)transaction{

    WLog(@"%@",transaction.transactionIdentifier);

    NSDictionary *parametersDict;
    NSString *username;
    NSString *nologinuser;
    NSString *orderId;
    NSString *productId;

    if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].dicMemberOrder[@"orderId"]] ) {
        orderId = @"";
    } else {
        orderId = [WShareUtil sharedData].dicMemberOrder[@"orderId"];
    }

    if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].productId]) {
        productId = @"";
    } else {
        productId = [WShareUtil sharedData].productId;
    }
    NSString *dto = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:@{@"cat":@"0",@"orderId":orderId,@"transaction_id":transaction.transactionIdentifier,@"product_id":productId}]];

    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"username":username,@"revert":@"iosorder",@"dto":dto}};
    } else {
        nologinuser = [WShareUtil getUUID];
        parametersDict = @{@"mode":@"native",@"service":@"order",@"content":@{@"apptype":@"ios",@"nologinuser":nologinuser,@"revert":@"iosorder",@"dto":dto}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];


    NSDictionary *parame = @{@"params":[CommonFunc encryptWithText:secret],@"receipt":receipt};

    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret],@"receipt":receipt} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if (![successStr isEqualToString:@"true"]) {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
        } else {
            [WShareUtil showAlert:@"温馨提示" message:@"购买成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:MEMBER_BNY_NOTIFY object:nil];
        }

        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        [WShareUtil showWait:NO frame:CGRectZero];
    } failure:^(NSError *error) {
        WLog(@"失败");
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        [WShareUtil showWait:NO frame:CGRectZero];
    } showProgress:NO];
}

////苹果客户端验证 receipt
//
//- (void)requestSubmitBuyInfoData:(NSString *)receipt transaction:transaction
//{
//    if(transaction==nil)
//    {
////        ShowAlertMessage(@"错误",@"发货失败，transaction为空，请与开发人员联系！",@"关闭");
//        WLog(@"transaction is null,please check");
//        return;
//    }
//
//
//    //applicationUser为空，将本次的订单号回传游戏平台
////    if(nil == order  || order.length == 0)
////    {
////        //如果本次不是通过重新点击支付生成订单，而是由重新登录检测到的未finish订单，将roleID回传游戏平台
////        if(nil == tempOrder  || tempOrder.length == 0)
////        {
////            if([RoleID isEqualToString:@"-1"])
////            {
////                //未进入游戏，订单号为空的情况不做处理
////                return;
////            }
////
////            if(nil == RoleID  || RoleID.length == 0)
////            {
////                //进入游戏后假设某种异常导致RoleID为空，提示玩家错误原因
////                ShowAlertMessage(@"错误",@"发货失败，RoleID为空，请与游戏开发人员联系！",@"关闭");
////                return;
////            }
////            paytype = @"OrderIsNull";
////            tempOrder=RoleID;
////        }
////        order=tempOrder;
////
////    }
//
//    if(nil == receipt  || receipt.length == 0)
//    {
////        ShowAlertMessage(@"错误",@"发货失败，recipt为空，请与开发人员联系！",@"关闭");
//        WLog(@"recipt is null or empty,please check");
//        return;
//    }
//
//    NSURL *nsUrl = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"]; //这里址就不写了
//
//    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:nsUrl];
//    [request setHTTPMethod:@"POST"];
//    NSMutableDictionary * dictionary = [[NSMutableDictionary alloc] init];
//    [dictionary setValue:receipt forKey:@"receipt-data"];
//    [dictionary setValue:@"b8f98fc8812f4b54a4ea22bbad099c66" forKey:@"password"];
//    NSError * orError = nil;
//    NSData * orData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&orError];
//    NSString *content = [[NSString alloc] initWithData:orData encoding:NSUTF8StringEncoding];
//    NSData * data =[content dataUsingEncoding:NSUTF8StringEncoding];
//    [request setHTTPBody:data];
//    NSURLResponse * response = nil;
//    NSError * error;
//    NSData * result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//
//    if(error == nil)
//    {
//        NSDictionary * dResult = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:nil];
//        int ret = [[dResult objectForKey:@"retCode"] intValue];
//
//        WLog(@"%@",[self dictionaryToJson:dResult]);
//        if(ret == 0)
//        {
//            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
//        }
//    }
//    else
//    {
//
//       //        ShowAlertMessage(@"错误",@"发货失败，与游戏平台通信错误，请与开发人员联系！",@"关闭");
//    }
//    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//
//    UIView *view = [appDelegate.window viewWithTag:58000];
//    [view removeFromSuperview];
//
//}
//
//- (NSString*)dictionaryToJson:(NSDictionary *)dic
//{
//    if (dic) {
//        NSError *parseError = nil;
//        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
//        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    }
//    return nil;
//}


@end
